package com.l.web.service.system.config;

import com.l.web.service.KeyUpdate;
import com.l.web.service.ResponseCode;
import com.l.web.service.ResponseInfo;
import com.l.web.service.ServiceSupport;
import org.apache.log4j.Logger;
import org.l.qiao.search.Query;
import org.l.qiao.search.Update;
import org.l.qiao.util.JSONConvert;

import java.util.Map;

public class ConfigUpdateService extends ServiceSupport {

    private static final Logger LOGGER = Logger.getLogger(ConfigUpdateService.class);
    private ConfigDAO configDAO;

    public void setConfigDAO(ConfigDAO configDAO) {
        this.configDAO = configDAO;
    }

    public String execute() {
        KeyUpdate keyUpdate = this.getKeyUpdate(Config.class);
        LOGGER.debug("修改信息信息：" + keyUpdate);

        if ("OPTION".equals(keyUpdate.getName())) {
            updateOption(keyUpdate);
        } else {
            update(keyUpdate);
        }

        return NONE;
    }

    private void update(KeyUpdate keyUpdate) {

        if (keyUpdate.check()) {
            int result;

            try {
                result = configDAO.update(keyUpdate);
            } catch (Exception e) {
                LOGGER.error("修改异常[" + keyUpdate + "]：" + e);
                result = ResponseCode.FAILURE;
            }

            ResponseInfo msg = new ResponseInfo(result);
            out(msg);
        } else {
            LOGGER.error("非法修改：" + keyUpdate);
            error(404);
        }
    }

    private void updateOption(KeyUpdate keyUpdate) {
        int result;
        Map map = null;

        try {
            map = JSONConvert.toMap(keyUpdate.getValue());
        } catch (Exception e) {
            LOGGER.error("非法修改：" + keyUpdate);
            return;
        }

        try {
            Query query = new Query();
            query.setId(keyUpdate.getId());
            Update update = new Update();
            update.put(keyUpdate.getKey(), map);
            result = configDAO.updateSetOne(query, update);
        } catch (Exception e) {
            LOGGER.error("修改配置详情异常[" + keyUpdate + "]：" + e);
            result = ResponseCode.FAILURE;
        }

        out(result);
    }
}
